/*
 * Copyright 2021 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	//"encoding/json"
	"bytes"
	"crypto/tls"
	"encoding/json"
	"os"
	"sample-application/src/common"
	"sample-application/src/controllers"
	"sample-application/src/model"
	"time"

	"fmt"

	"net/http"

	"github.com/astaxie/beego"
	log "github.com/sirupsen/logrus"
)

func main() {

	fmt.Println("In the main function")

	time.Sleep(time.Second * 10) //3 mins delay for profile stack coming up
	err := registerCallback()
	if err != nil {
		return
	}

	beego.Run()
}

func init() {
	beego.Router("/telemtry/data", &controllers.MainController{}, "post:ProcessData")
}

func registerCallback() error {

	url := common.HTTPEXPORTER

	var callBackInfo model.CallBackInfo

	callBackInfo.Url = common.CALLBACK
	//callBackInfo.Node = common.NODE
	callBackInfo.Node = os.Getenv("NODE")

	fmt.Println(url)
	fmt.Println(callBackInfo)

	data, err := json.Marshal(callBackInfo)
	if err != nil {
		log.Error(err)
		return err
	}

	responseBody := bytes.NewReader(data)

	req, errNewRequest := http.NewRequest("POST", url, responseBody)
	if errNewRequest != nil {
		log.Error("Failed to send the request", errNewRequest)
		return errNewRequest
	}

	response, errDo := DoRequest(req)
	if errDo != nil {
		log.Error("Failed to send the request", errDo)
		return errDo
	}

	defer response.Body.Close()
	return nil
}

// Update tls configuration
func TLSConfig() (*tls.Config, error) {
	return &tls.Config{
		InsecureSkipVerify: true,
	}, nil
}

// Does https request
func DoRequest(req *http.Request) (*http.Response, error) {
	config, err := TLSConfig()
	if err != nil {
		log.Error("Unable to send request")
		return nil, err
	}

	tr := &http.Transport{
		TLSClientConfig: config,
	}
	client := &http.Client{Transport: tr}

	return client.Do(req)
}
